// @ts-nocheck
<template>
  <div class="mePage">
    <CommonHeader :balance="balance" />
    <div class="guset_id" v-if="!authStore.isrealLogin">Guest ID: {{ guset_id }}</div>
    <!-- <div class="guset_id" v-else>{{ authStore.userInfo }}</div> -->
    <div class="tips_wrap" v-if="!authStore.isrealLogin">
      <img src="@/assets/images/normal_pic@2x.png" alt="" />
      <p>Please login to retain membership.</p>
    </div>
    <div class="login_wrap" v-if="!authStore.isrealLogin">
      <van-button plain type="primary" class="sign_in" @click="goSignIn">Sign in</van-button>
      <van-button plain type="primary" class="login_btn" @click="goLogin">Login</van-button>
    </div>
    <!-- 登录成功后显示 -->
    <div class="login_show_top" v-else>
      <img :src="useInfo.avatar" alt="" class="person_img" v-if="useInfo.avatar" />
      <img src="@/assets/images/normal_pia@2x.png" alt="" class="person_img" v-else />
      <div class="emai_wrap">
        <span class="email">{{ useInfo.username }}</span>
        <img src="@/assets/images/icon_edit@2x.png" alt="" class="edit_img" v-if="false" />
      </div>
    </div>
    <!-- my creation -->
    <div class="my_create" v-if="haveCreationList.length">
      <p class="title">My Creation</p>
      <div class="img_wrap">
        <div class="inner_img" @click="removeBlur">
          <img :src="haveCreationList[0].resultFileUrl" alt=""
            @click="previewImage([haveCreationList[0].resultFileUrl])" class="bg_img"
            :class="{ 'glass-effect': !isPay }" />
          <img src="@/assets/images/ic_close@2x.png" alt="" class="close_img" @click="deleteImg" v-if="false" />
          <img src="@/assets/images/icon_download_w@2x.png" class="downLoad" v-if="isPay"
            @click="handleDownload(image1)" />
        </div>
      </div>
      <!-- 确认按钮 -->
      <ComfirmBtn v-if="!isPay" btnName="Remove Blur" :gemsNum="balance" :diamondNum="diamondNum"
        :isShowDiamond="isShowDiamond" @comfrim="removeBlur" />
      <div class="remove_blur" v-if="!isPay">
        <span class="text">Remove blur only 1</span>
        <img src="@/assets/images/Diamond icon@2x.png" />
      </div>
    </div>
    <!-- AI is creating…… -->
    <div class="ai_creating" v-if="creatingList.length">
      <div class="title">AI is creating……</div>
      <ul class="ai_creating_ul">
        <li v-for="(item, index) in creatingList" :key="index">
          <img :src="item.originFileUrl" alt="" />
          <!-- 遮罩层 loading -->
          <div class="cover_top">
            <img src="@/assets/images/ic_ref@2x.png" />
          </div>
        </li>
      </ul>
    </div>
    <!-- History -->
    <div class="history_wrap" ref="scrollContainer" v-if="haveCreationList.length > 1" style="overflow-y: auto;">
      <div class="title">My Creation</div>
      <ul class="img_ul">
        <li v-for="(item, index) in haveCreationList" :key="item.id" @click="previewImage([item.resultFileUrl])">
          <img :src="item.resultFileUrl" class="img" />
          <img src="@/assets/images/ic_close@2x.png" alt="" class="delete" @click="deleteImg(index)" v-if="false" />
          <img src="@/assets/images/icon_download_w@2x.png" class="downLoad"
            @click.stop="handleDownload(item.resultFileUrl)" />
        </li>
      </ul>
      <!-- 加载状态提示 -->
      <!-- <div v-if="pagination.isLoading" class="loading-indicator">
        <van-loading type="spinner" size="32px" />
      </div> -->
    </div>
  </div>
</template>

<script setup>
import CommonHeader from "@/components/CommonHeader.vue";
import ComfirmBtn from "@/components/ComfirmBtn.vue";
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import { showImagePreview, showConfirmDialog } from "vant";
import { useAuthStore } from "@/stores/authStore";
import "vant/es/image-preview/style";
import image1 from "@/assets/images/pic@2x (5).png";
import api from "@/api";
import { trackEvent } from "@/utils/firebase";
import { downloadImg } from "@/utils/handleDownload";
import router from "@/router";

const authStore = useAuthStore();
const guset_id = ref("");

const goLogin = () => {
  authStore.showLoginDialog(); // 触发登录弹窗
  authStore.isLogin = true;
};
const goSignIn = () => {
  authStore.showLoginDialog(); // 触发注册弹窗
  authStore.isLogin = false;
};

const diamondNum = ref("100");
const isShowDiamond = ref(true);

// 是否充值，如果没有充值，图片就模糊
const isPay = ref(false);

const removeBlur = () => {
  // 点击按钮，钻石充足，执行工作流
  if (Number(balance.value) >= 100) {
    // 扣除100钻石，显示清晰的图片
    balance.value = String(Number(balance.value) - 100);
    // 显示
    isPay.value = true;
  } else {
    trackEvent("我的_生成结果_点击【Remove Blur】", { id: "100051" }); //埋点
    //钻石不足，跳往充值有页
    router.push("./myDiamonds");
  }
};

// 图片下载
const handleDownload = (imgUrl) => {
  downloadImg(imgUrl, "myCreate");
};

// 图片预览
const previewImage = (images, startPosition = 0) => {
  if (isPay.value) {
    showImagePreview({
      images, // 图片 URL 数组
      startPosition, // 初始展示的图片索引（多图时必传）
      closeable: true, // 关闭按钮
      closeIconPosition: "top-right", // 指定右上角位置
      onClose: () => console.log("预览关闭"),
      // 其他配置：maxZoom: 3（缩放比例）、showIndex: true（显示页码）等
    });
  }
};

// 删除确认弹框
const deleteImg = (index) => {
  console.log(index);
  showConfirmDialog({
    message: "Are you sure you want to delete?",
    className: "custom-delete-dialog",
    confirmButtonText: "Delect",
    cancelButtonText: "Cancel",
  })
    .then(() => {
      // on confirm
    })
    .catch(() => {
      // on cancel
    });
};

// 用户信息
const balance = ref("");
const useInfo = ref({});
const getUseInfo = async () => {
  try {
    const response = await api.userInfo();
    balance.value = String(response.data.balance);
    useInfo.value = response.data;
    if (response.data.rechargeStatus === 1) {
      isPay.value = true;
    } else {
      isPay.value = false;
    }
  } catch (err) {
    console.log(err);
  }
};
// 获取任务列表
// 加一个状态过滤，status  任务状态(10:待处理,20:处理中,30:已取消,40:超时,50:重试中,60:成功,70:失败)
const creatingList = ref([]);
const haveCreationList = ref([]);

// 分页相关状态
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  hasMore: true,
  isLoading: false,
});

// 滚动容器引用
const scrollContainer = ref(null);

const getTaskPage = async (page = 1, size = 10) => {
  try {
    pagination.value.isLoading = true;
    const response = await api.taskPage({ page, size });
    // 合并新数据  筛选 status=60 成功
    haveCreationList.value = [
      ...haveCreationList.value,
      ...response.data.filter((item) => item.status === 60),
    ];
    // 合并新数据  筛选 status=60 成功
    creatingList.value = [
      ...creatingList.value,
      ...response.data.filter((item) => item.status === 10),
    ];
    // 更新分页状态
    pagination.value.hasMore = response.data.length === size;
    pagination.value.currentPage = page;
  } catch (err) {
    console.log(err);
  } finally {
    pagination.value.isLoading = false;
  }
};

// 滚动到底部触发加载
const handleScroll = () => {
  if (pagination.value.isLoading || !pagination.value.hasMore) return;
  const container = scrollContainer.value;
  const scrollTop = container.scrollTop;
  const scrollHeight = container.scrollHeight;
  const clientHeight = container.clientHeight;

  // 判断是否滚动到底部（预留10px缓冲）
  if (scrollTop + clientHeight >= scrollHeight - 10) {
    pagination.value.currentPage += 1;
    getTaskPage(pagination.value.currentPage, pagination.value.pageSize);
  }
};

// 新增响应式变量控制滚动监听状态
const shouldListenScroll = ref(false);

// 监听 haveCreationList 变化
watch(
  haveCreationList,
  (newVal) => {
    if (newVal.length > 1 && !shouldListenScroll.value) {
      nextTick(() => {
        scrollContainer.value?.addEventListener("scroll", handleScroll);
        shouldListenScroll.value = true;
      });
    } else if (newVal.length <= 1 && shouldListenScroll.value) {
      scrollContainer.value?.removeEventListener("scroll", handleScroll);
      shouldListenScroll.value = false;
    }
  },
  { immediate: true }
); // 立即执行初始检查

onMounted(() => {
  guset_id.value = localStorage.getItem("baseFingerprint")
    ? localStorage.getItem("baseFingerprint")
    : "";
  // console.log("用户信息:", localStorage.getItem("auth-store"));
  // 查询用户信息
  getUseInfo();
  // 任务列表
  getTaskPage();
  trackEvent("展示_我的", { id: "100050" }); //埋点
});

onUnmounted(() => {
  // 移除滚动监听
  scrollContainer.value?.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
/* 新增加载状态样式 */
.loading-indicator {
  text-align: center;
  padding: 16px;
  background: #fff;
  margin-top: 10px;
}

/* 调整容器高度 */
.history_wrap {
  max-height: calc(100vh - 70px);
  overflow-y: auto;
}

.mePage {
  width: 100%;
  box-sizing: border-box;
  padding: 80px 16px 30px 16px;
  min-height: 100vh;
  /* 背景图设置 */
  background-image: url("../assets/images/bg_texture@2x.png");
  background-position: top center;
  /* 从顶部开始 */
  background-repeat: no-repeat;
  /* 不重复 */
  background-size: 100% auto;
  /* 宽度满屏，高度自适应 */
  background-color: #fbfbfd;

  .guset_id {
    font-size: 20px;
    color: rgba(0, 0, 0, 0.95);
    text-align: center;
    line-height: 24px;
    font-weight: 600;
  }

  .tips_wrap {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 12px;

    img {
      width: 24px;
      margin-right: 9px;
    }

    p {
      font-size: 14px;
      color: #6251ff;
    }
  }

  .login_wrap {
    justify-content: center;
    align-items: center;
    text-align: center;
    margin-top: 8px;

    .van-button {
      border: 0;
      font-weight: 700;
      width: 88px;
      height: 40px;
      line-height: 40px;
      background: #6251ff;
      border-radius: 28px 28px 28px 28px;
      font-size: 12px;
      color: #ffffff;
    }

    .sign_in {
      margin-right: 16px;
    }
  }

  .login_show_top {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .person_img {
      width: 80px;
      margin-bottom: 13px;
    }

    .emai_wrap {
      display: flex;
      justify-content: center;
      align-items: center;

      .email {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.95);
        margin-right: 4px;
      }

      .edit_img {
        width: 24px;
      }
    }
  }

  .my_create {
    margin-top: 24px;
    width: 100%;
    background: rgba(255, 255, 255, 0.45);
    box-shadow: inset 0px 1px 0px 0px rgba(255, 255, 255, 0.45);
    border-radius: 12px;
    box-sizing: border-box;
    padding: 20px 34px;

    .title {
      font-weight: 600;
      margin-bottom: 16px;
      text-align: center;
      font-size: 16px;
      color: rgba(0, 0, 0, 0.75);
    }

    .img_wrap {
      position: relative;
      width: 217px;
      height: 217px;
      margin: 0 auto;
      margin-top: 14px;
      overflow: hidden;
      display: flex;
      justify-content: center;
      align-items: center;

      /* border-radius: 12px; */
      .inner_img {
        width: 100%;
        height: 100%;
        border: 4px solid;
        display: flex;
        justify-content: center;
        align-items: center;
        border-image: linear-gradient(90deg,
            rgba(255, 213, 47, 1),
            rgba(248, 116, 255, 1),
            rgba(81, 110, 255, 1)) 4 4;

      }

      .bg_img {
        max-width: 100%;
        /* 限制最大宽度为容器宽度 */
        max-height: 100%;
        /* 限制最大高度为容器高度 */
        width: auto;
        /* 保持原始宽度比例 */
        height: auto;
        /* 保持原始高度比例 */
        object-fit: contain;
        /* 保持比例，完整显示图片 */
      }

      .close_img {
        width: 24px;
        position: absolute;
        right: 10px;
        top: 10px;
      }

      .downLoad {
        width: 24px;
        position: absolute;
        right: 8px;
        bottom: 8px;
      }
    }

    .glass-effect {
      /* 图片模糊设置 */
      filter: blur(10px);
      transition: filter 0.5s;
    }
  }

  .remove_blur {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 31px;

    .text {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.95);
      margin-right: 4px;
      line-height: 17px;
    }

    img {
      width: 16px;
    }
  }

  .ai_creating {
    margin-top: 23px;

    .title {
      font-size: 16px;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.75);
      font-weight: 600;
      margin-bottom: 10px;
    }

    .ai_creating_ul {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;

      li {
        width: 111px;
        margin-right: 5px;
        position: relative;
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
          max-width: 100%;
          /* 限制最大宽度为容器宽度 */
          max-height: 100%;
          /* 限制最大高度为容器高度 */
          width: auto;
          /* 保持原始宽度比例 */
          height: auto;
          /* 保持原始高度比例 */
          object-fit: contain;
          /* 保持比例，完整显示图片 */
        }

        .cover_top {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
          background: rgba(255, 255, 255, 0.65);
          box-sizing: border-box;
          display: flex;
          justify-content: center;
          align-items: center;

          img {
            width: 38px;
            height: 38px;
          }
        }
      }

      li:last-child {
        margin-right: 0;
      }
    }
  }

  .history_wrap {
    margin-top: 24px;

    .title {
      font-weight: 600;
      margin-bottom: 8px;
      font-size: 16px;
      color: rgba(0, 0, 0, 0.75);
      line-height: 22px;
    }

    .img_ul {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;

      li {
        position: relative;
        width: 168px;
        margin-bottom: 12px;
        display: flex;
        justify-content: center;
        align-items: center;

        .img {
          max-width: 100%;
          /* 限制最大宽度为容器宽度 */
          max-height: 100%;
          /* 限制最大高度为容器高度 */
          width: auto;
          /* 保持原始宽度比例 */
          height: auto;
          /* 保持原始高度比例 */
          object-fit: contain;
          /* 保持比例，完整显示图片 */
        }

        .delete {
          position: absolute;
          width: 24px;
          right: 10px;
          top: 10px;
        }

        .downLoad {
          position: absolute;
          right: 8px;
          bottom: 8px;
          width: 24px;
        }
      }
    }
  }
}
</style>
